<template>
  <div class="artist-list">
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <van-cell
          v-for="(item, index) in list"
          :key="index"
          :title="item.title"
          @click="toDetail(item.art_id)"
        >
          <template #label>
            <!-- 主体内容区域 -->
            <van-grid :border="false" :column-num="item.cover.type">
              <van-grid-item
                v-for="(it, index) in item.cover.images"
                :key="index"
              >
                <van-image lazy-load fit="cover" :src="it" />
              </van-grid-item>
            </van-grid>
            <!-- 底部额外信息区域 -->
            <div class="meta">
              <!-- 左侧 -->
              <div class="info-box">
                <span>{{ item.aut_name }}</span>
                <span>{{ item.comm_count }} 评论</span>
                <span>{{ item.pubdate | fromNow }}</span>
              </div>
              <!-- 右侧 -->
              <van-icon name="cross"></van-icon>
            </div>
          </template>
        </van-cell>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArticle } from '../../api/home'
import moment from 'moment'
moment.locale('zh-cn')
export default {
  name: 'articleList',
  props: ['channelId'],
  data () {
    return {
      list: [],
      loading: false,
      finished: false,
      refreshing: false,
      timestamp: undefined
    }
  },
  methods: {
    toDetail (id) {
      this.$router.push({ name: 'article', params: { id } })
    },
    async onLoad () {
      if (this.timestamp === undefined) {
        this.timestamp = Date.now()
      }
      const res = await getArticle({
        channel_id: this.channelId,
        timestamp: this.timestamp
      })
      // console.log(res)
      // 下拉刷新的判断
      if (this.refreshing) {
        this.list = []
        this.refreshing = false
      }
      // 添加数据
      this.list.push(...res.data.data.results)
      this.timestamp = res.data.data.pre_timestamp
      this.loading = false
      // 最多100个
      if (this.list.length >= 100) {
        this.finished = true
      }
    },
    onRefresh () {
      // 清空列表数据
      this.finished = false

      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      this.loading = true
      this.onLoad()
    }
  },
  created () {
    // console.log('channelId', this.channelId)
  }
  // 已设置全局的fromNow过滤器
  // filters: {
  //   fromNow (value) {
  //     return moment(value).fromNow()
  //   }
  // }
}
</script>

<style lang="less">
.artist-list {
  .meta {
    display: flex;
    justify-content: space-between;
    span {
      margin-right: 10px;
    }
  }
}
</style>
